#!/usr/bin/env python
#coding=utf-8

import getpass
import pickle

def open_database():
    try:
        with open('passwd.pkl','rb') as f:
            return pickle.load(f)
    except IOError as e:
            return False
    except Exception as e:
            raise e

   
def update_database(user_data):
    try:
        with open('passwd.pkl','wb') as f:
        pickle.dump(user_data,f)
        return True
    except IOError as e:
        return False
    except Exception as e:
        raise e
            

def register():
    username = input("请输入用户名：")
    user_data = open_database() if open_database() else {}
    if username in user_data.keys():
        print("用户名已存在！")
        return False
    user_passwd = getpass.getpass("请输入密码：")
    user_data[username] = user_passwd
    db_status = update_database(user_data)
    if not db_status:
        print("注册失败！")
    print("注册成功！")


def login():
    count = 0
    while count < 3:
        username = input("请输入用户名：")
        user_passwd = getpass.getpass("请输入密码:")
        user_data = open_database()
        passwd = user_data.get(username)
        if passwd is None:
            print("用户不存在！")
            break
        if user_passwd != passwd:
            count += 1
            print("密码错误，请重试！（最多重试3次）")
            continue
        print("密码正确")
        break
    else:
        print("已经3次  退出")
        
        
if __name__ = '__main__':
    while True:
        user_choice = input("1、注册，2、登陆，0、退出：")
        if user_choice == "1":
            register()
        elif user_choice == "2":
            login()
        else:
            break
